#include "PageCache.h"

PageCache PageCache::_sInst;

// 获取一个k页的span
Span *PageCache::NewSpan(size_t k)
{
    assert(k > 0 && k < NPAGES);

    // 先检查第k个桶里有没有span
    if (!_spanlists[k].Empty())
    {
        return _spanlists[k].PopFront();
    }

    // 检查后面的桶里有没有span，如果有可以对它进行切分
    for (size_t i = k + 1; i < NPAGES; ++i)
    {
        if (!_spanlists[i].Empty())
        {
            Span *nSpan = _spanlists[i].PopFront();
            Span *kSpan = new Span;

            // 再nSpan的头部切一个k页下来
            // k页span返回
            // n - k页挂在对应映射的位置

            kSpan->_pageId = nSpan->_pageId;
            kSpan->_n = k;

            nSpan->_pageId += k;
            nSpan->_n -= k;

            return kSpan;
        }
    }

    // 走到这个位置说明后面没有大页的span了
    // 这时候就去堆上申请一个128页的span
    Span *bigSpan = new Span;
    void *ptr = SystemAlloc(NPAGES - 1);
    bigSpan->_freeList = ptr;
    bigSpan->_pageId = (PAGE_ID)ptr >> PAGE_SHIIFT;
    bigSpan->_n = NPAGES - 1;

    _spanlists[bigSpan->_n].PushFront(bigSpan);

    return NewSpan(k);
}

// 获取从对象到span的映射
Span* PageCache::MapObjectToSpan(void *obj)
{
    PAGE_ID id = ((PAGE_ID)obj << PAGE_SHIIFT);
    auto ret = _idSpanMap.find(id);
    if (ret != _idSpanMap.end())
    {
        return ret->second;
    }
    else
    {
        assert(false);
        return nullptr;
    }
}

// 释放空闲span回到Pagecache，并合并相邻的span
void PageCache::ReleaseSpanToPageCache(Span *span)
{
    // 对span前后的页，尝试进行合并，缓解内存碎片问题

    while(1)
    {
        PAGE_ID prevId = span->_pageId - 1;
        auto ret = _idSpanMap.find(prevId);

        // 前面的页没有了，不合并
        if (ret == _idSpanMap.end())
        {
            break;
        }

        // 前页相邻的span在使用，不合并
        Span* prevSpan = ret->second;
        if (prevSpan->_isUse == true)
        {
            break;
        }

        // 合并出超过128页的span没办法管理，不合并了
        if (prevSpan->_n + span->_n > NPAGES - 1)
        {
            break;
        }

        span->_pageId = prevSpan->_pageId;
        span->_n += prevSpan->_n;

        _spanlists[prevSpan->_n].Erase(prevSpan);
        delete prevSpan;
    }


    // 向后合并
    while (1)
    {
        PAGE_ID nextId = span->_pageId + span->_n;
        auto ret = _idSpanMap.find(nextId);

        if (ret == _idSpanMap.end())
        {
            break;
        }

        Span* nextSpan = ret->second;
        if (nextSpan->_isUse == true)
        {
            break;
        }

        if (nextSpan->_n + span->_n > NPAGES - 1)
        {
            break;
        }


        span->_n += nextSpan->_n;

        _spanlists[nextSpan->_n].Erase(nextSpan);

        delete nextSpan;
    }


    _spanlists[span->_n].PushFront(span);
    span->_isUse = false;
    _idSpanMap[span->_pageId] = span;
    _idSpanMap[span->_pageId + span->_n - 1] = span;
}